<template>
    <div class="activity">
        <cube-scroll>
            <!--S主体-->
            <cube-scroll id="main-scroll" ref="scroll" :style="{height:page_height+'px'}">
                <div id="map" ref="map"></div>
            </cube-scroll>
            <!--E主体-->

            <!--S各种操作按钮-->
                <!--S开宝箱-->
                <cube-button id="open-btn" @click="clickOpenBtn">
                    开宝箱
                </cube-button>
                <!--E开宝箱-->
                <!--S可开和已开宝箱-->
                <div id="can-open-number" v-if="activity_data.init_bz_number > 0">可开宝箱:{{bz.already_open_number}}/{{bz.can_open_number}}</div>
                <!--E可开和已开宝箱-->
            <!--E各种操作按钮-->

            <!--S头部状态-->
            <div id="header">
                <div class="child"><router-link class="a" :to="'/activity/explain/'+activity_id">活动说明</router-link></div>
                <div class="child" v-if="activity_data.time_status != 2">
                    <template v-if="activity_data.time_status == 1">未开始</template>
                    <template v-else>活动已结束</template>
                </div>
                <div class="child" v-show="bz.distance > 0 && bz.selected_bz != null">距离:{{str_distance}}</div>
            </div>
            <!--E头部状态-->

            <!--S开宝箱-->
            <div id="open-bz" v-show="open.step != 0">

                <!--S开宝箱中...-->
                <div class="open-bz opening" v-show="open.step == 1">
                    <img class="animated infinite bounce icon" src="./images/open-loading.png" />
                    <h3>请稍等...宝箱开启中</h3>
                </div>
                <!--E开宝箱中...-->

                <!--S成功开宝箱-->
                <div class="open-bz opened" v-show="open.step == 2">

                    <!--S开宝箱成功-->
                    <template v-if="open.bz.status == 'success'">
                        <!--S宝藏和实物奖励-->
                        <template v-if="open.bz.type == 1 || open.bz.type == 2">
                            <img class="animated zoomInDown icon" :src="open.bz.icon" />
                            <h3>恭喜您，获得{{open.bz.name}}</h3>
                        </template>
                        <!--E宝藏和实物奖励-->
                        <!--S门店卡券-->
                        <template v-if="open.bz.type == 3">
                        <div class="animated zoomInDown">
                            <div class="store" :class="open.bz.coupon_type">
                                <img class="logo" :src="open.bz.store_logo" >
                                <p class="name">{{open.bz.store_name}}</p>
                            </div>
                            <div class="coupon" :class="open.bz.coupon_type">
                                <div class="type">{{open.bz.cost_type}}</div>
                                <img v-if="open.bz.cover" class="cover" :src="open.bz.cover" />
                                <div class="cost">{{open.bz.cost}}</div>
                                <div class="name">{{open.bz.name}}</div>
                                <div class="time">{{open.bz.period}}</div>
                            </div>
                            <h3>恭喜您，获得卡券一张</h3>
                        </div>
                        </template>
                        <!--E门店卡券-->

                        <!--S活动后台卡券-->
                        <template v-if="open.bz.type == 4">
                            <div class="sponsor-coupon animated zoomInDown">
                                <img class="icon" :src="open.bz.icon" >
                                <div class="name">{{open.bz.name}}</div>
                                <div class="time">{{open.bz.period}}</div>
                            </div>
                            <h3>恭喜您，获得卡券一张</h3>
                        </template>
                        <!--S活动后台卡券-->

                    </template>
                    <!--E开宝箱成功-->

                    <!--S开宝箱错误-->
                    <template v-if="open.bz.status == 'error'">
                        <svg class="error-iconfont animated zoomInDown" aria-hidden="true">
                            <use xlink:href="#icon-cuowutishi1"></use>
                        </svg>
                        <h3>{{open.bz.err_msg}}</h3>
                    </template>
                    <!--E开宝箱错误-->
                    <span class="close cubeic-close" @click="open.step = 0"></span>
                </div>
                <!--E成功开宝箱-->

            </div>
            <!--E开宝箱-->

            <!--S启动广告-->
            <div id="adver" @click="clickAdver" v-if="adver.show" :style="{'background-image':'url('+adver.src+')'}">
                <div class="down">{{adver.down}}秒后关闭</div>
            </div>
            <!--E启动广告-->

            <!--S左侧控制面板-->
            <console :activity-id="activity_id"></console>
            <!--E左侧控制面板-->

            <!--S右下角控制区域-->
            <control :activity-id="activity_id" :open-share="share.open_share" :shop-model="activity_data.shop_model" @activityLocation="activityLocation" @userLocation="userLocation" @showFriend="showFriend"></control>
            <!--E右下角控制区域-->

            <!--S好友列表-->
            <transition :name="friend_list.friend_transition">
                <keep-alive include="friend">
                    <friend :activity-id="activity_id" :init-bz-number="activity_data.init_bz_number" v-if="friend_list.show" @close="closeFriend" @award="friendAward"></friend>
                </keep-alive>
            </transition>
            <!--E好友列表-->

            <!--S子页面-->
            <transition :name="transition_name">
                <router-view class="children" />
            </transition>
            <!--E子页面-->

        </cube-scroll>
    </div>
</template>

<script>
import store from "../../store";
import Md5 from "md5";
import random from "random";
import friend from "./components/friend/Friend";
import console from "./components/console/Console";
import control from "./components/control/Console";
export default {
    name:"activity",
    data(){
        return {
            transition_name:"",  //页面切换动画
            page_height:document.documentElement.clientHeight,
            uid:this.$sysinfo.uid,
            activity_id:0,  //活动id
            share_uid:0,  //分享用户的uid
            //S地图相关
            map:{
                map:null,  //高德地图对象
                location:null,  //高德定位对象
                user_mark:null,  //用户mark标记对象
            },
            //E地图相关
            //活动数据
            activity_data:{
                cache:0,  //数据是否来自缓存
                open3d:0,  //活动是否开启了3d模式
                shop_model:0,  //是开启了商场模式
                open_distance:0,  //打开宝箱的距离
                time_status:0,  //活动时间段状态 1=未开始 2=进行中 3=已结束
                bz_number:0,   //地图宝藏投放的数量
                init_bz_number:0,  //用户可开的宝箱数量
                map_coords:[],    //活动选择的区域集合
                map_coords_index:0   //当前活动区域的下标
            },
            //活动ui
            ui:{
                skin:""
            },
            //分享相关
            share:{
                share_uid:0,   //分享的用户id
                share_take:0,   //是否达成分享奖励条件
                take_m:0,   //分享生效距离
                open_share:0  //是否开启了海报分享
            },
            //广告
            adver:{  //启动广告
                show:false,  //广告显示状态
                url:"",  //广告链接
                src:"", //广告图片地址
                down:5  //倒计时秒数
            },
            //S宝箱相关
            bz:{
                /**
                 * 宝藏的所有坐标点
                 * bz_lnglat[
                 * {lnglat:[lng,lat],number:0},  //区域一的所有坐标点  lnglat所有坐标  number坐标点数量
                 * {lnglat:[lng,lat],number:0}    //区域二的所有坐标点  lnglat所有坐标  number坐标点数量
                 * ]
                 */
                lnglat:[],
                //宝箱的默认样式
                default_style:`<div class="default_bz_style">
                                 <svg class="iconfont self-iconfont" aria-hidden="true">
                                    <use xlink:href="#icon-baoxiang-01"></use>
                                 </svg>
                               </div>`,
                //点击宝箱后的样式
                selected_style:`<div class="default_bz_style selected_bz_style animated infinite pulse">
                                 <svg class="iconfont self-iconfont" aria-hidden="true">
                                    <use xlink:href="#icon-baoxiang-01"></use>
                                 </svg>
                                </div>`,
                //当前选择的宝箱对象
                selected_bz:null,
                //宝藏到用户的距离
                distance:0,
                //用户可开宝箱的总数量
                can_open_number:0,
                //已开宝箱的总数
                already_open_number:0
            },
            //E宝箱相关
            //S开宝箱
            open:{
                step:0,  //0=正常状态  1=开宝箱中  2=开箱成功
                bz:{},   //返回的宝藏打开状态和打开的宝藏信息
                //bz:{type:3,status:'success',name:'卡券名称卡券名称卡券名称',store_name:'门店名字门店名字门店名字门店名字',store_logo:'https://w7dev.kuyuan.vip/attachment/images/2/2019/12/NVH8ZoVod2uAcDt2lTqh6vHHTdu6qq.png',coupon_type:'zk',cost:'满3000减300',cost_type:'满减',period:'有效期至2019-12-23',use_limit_type:'2'},
                //bz:{type:4,status:'success',name:'卡券名字卡券名字卡券名字',icon:'https://www.baidu.com/img/bd_logo1.png',period:'永久有效'}
                //bz:{status:'error',err_msg:'错误信息'}   //宝藏数据
                //bz:{status:'success',name:'金元宝',icon:'https://www.baidu.com/img/bd_logo1.png'}
            },
            //E开宝箱
            //好友列表
            friend_list:{
                show:false,
                friend_transition:"friend-transition animated slideInRight faster"
            }
        };
    },
    components:{
      friend,
      console,
      control
    },
    watch:{
      "$route"(to){
          if(to.name == "activity"){
              this.page_height = document.documentElement.clientHeight;
          }
      }
    },
    created(){
        var {activity_id,share_uid} = this.$route.params;
        this.activity_id = activity_id;
        this.share.share_uid = parseInt(share_uid);
    },
    mounted(){
        this.page_height = document.documentElement.clientHeight;
        this.getState()
            .then(()=>{
                this.startAdver();
            })
            .then(()=>{
                return this.get();  //活动信息
            })
            .then(()=>{
                return this.loadMap();  //加载地图
            })
            .then(()=>{
                return this.wxReady();  //微信执行ready
            })
            .then(()=>{
                return this.location();   //用户定位
            })
            .then((position)=>{
                this.createUserMark(position);  //创建用户mark
                return this.testShareValid(position);   //测试分享奖励条件
            })
            .then(()=>{
                return this.register();  //注册活动用户
            })
            .then(()=>{
                if(this.activity_data.init_bz_number != 0){
                    return this.getUserOpenBzNumber();  //获取用户可开宝箱和已开宝箱
                }
            })
            .then(()=>{
                if(!this.$sysinfo.develop) this.shareSetting();  //设置微信分享
            })
            .then(()=>{
                this.listenUserLocation();  //实时监听用户位置
            })
            .then(()=>{
                //设置宝藏的所有坐标
                return this.setBzLngLat();
            })
            .then(()=>{
               //插入宝藏
               this.pushBz();
            })
            .catch(error=>{
                if(error == "empty_activity"){
                    this.$router.replace("/");
                }
            });
        setTimeout(()=>{
            this.page_height = document.documentElement.clientHeight;
        },100);
    },
    computed:{
        //格式化宝箱到用户的距离
        str_distance(){
            var dis = "";
            if(this.bz.distance >= 1000){
                dis = (this.bz.distance/1000).toFixed(2)+"千米";
            }else{
                dis = this.bz.distance.toFixed(2)+"米";
            }
            return dis;
        },
        //格式化系统可开宝箱
        str_open_distance(){
            var dis = "";
            if(this.activity_data.open_distance >= 1000){
                dis = (this.activity_data.open_distance/1000)+"千米";
            }else{
                dis = this.activity_data.open_distance+"米";
            }
            return dis;
        }
    },
    //卸载页面
    beforeDestroy(){
        clearInterval(store.state.user_mark_timer);
    },
    //切换页面动画
    beforeRouteUpdate(to, from, next){
        this.transition_name = to.meta.sort > from.meta.sort ? "animated slideInRight faster delay-2s" : "animated slideOutRight faster delay-2s";
        setTimeout(()=>{
            next();
        },10);
    },
    methods:{
        //S活动状态
            //获取活动状态
            getState(){
                return new Promise((success,error)=>{
                    this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                        pages:"activity",
                        doing:"easyFind",
                        activity_id:this.activity_id,
                        return:["status"]
                    }))
                        .then((res)=>{
                            if(res.data.status == "success"){
                                if(res.data.data.status == 1){
                                    success();
                                }else{
                                    error("empty_activity");
                                }
                            }
                        })
                        .catch();
                });
            },
        //E活动状态

        //S加载---------
            //加载活动信息
            get(){
                return new Promise((success,error)=>{
                    this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                        pages:"activityA",
                        doing:"get",
                        activity_id:this.activity_id,
                    }))
                        .then((res)=>{
                            if(res.data.status == "success"){
                                var data = res.data.data;
                                this.activity_data = {
                                    cache:res.data.cache,
                                    open3d: parseInt(data.open3d),
                                    shop_model:parseInt(data.shop_model),
                                    time_status:data.time_status,
                                    open_distance:parseInt(data.open_distance),
                                    init_bz_number:parseInt(data.init_bz_number),
                                    bz_number:parseInt(data.bz_number),
                                    map_coords:data.map_coords,
                                    map_coords_index:0   //当前活动区域的下标
                                };
                                if(data.ui) this.ui = data.ui;
                                store.state.activity.map_coords = data.map_coords;
                                store.state.activity.time_status = data.time_status;
                                this.share.take_m = parseInt(data.take_m);
                                this.share.open_share = parseInt(data.open_share);
                                success();
                            }else{
                                error("获取活动失败");
                            }
                        })
                        .catch();
                });
            },
            //加载地图
            loadMap(){
                return new Promise((success)=>{
                    var mapData = {
                        zoom:18,
                        center:this.activity_data.map_coords[this.activity_data.map_coords_index].center,
                        mapStyle:"amap://styles/"+this.ui.skin
                    };
                    if(this.activity_data.open3d){
                        mapData.viewMode = "3D";
                        mapData.pitch = 70;
                    }
                    this.map.map = new this.$map.Map("map",mapData);
                    if(this.activity_data.open3d){
                        this.map.map.plugin(["AMap.ControlBar"],()=>{
                            var controlBar = new this.$map.ControlBar({
                                position:{
                                    bottom:"0",
                                    left:"-90px"
                                },
                                showControlButton:true
                            });
                            this.map.map.addControl(controlBar);
                        });
                    }
                    //创建高德地图定位对象
                    if(this.$sysinfo.develop) this.createMapLocation();
                    success();
                });
            },
            //创建高德地图定位对象
            createMapLocation(){
                store.state.location = this.map.location = new this.$map.Geolocation({
                    showButton:false,
                    showMarker:false,
                    showCircle:false,
                    panToLocation:false
                });
                this.map.map.addControl(this.map.location);
            },
            //微信ready
            wxReady(){
                if(!this.$sysinfo.develop){
                    return new Promise((success)=>{
                        this.$wx.ready(()=>{
                            success();
                        });
                    });
                }else{
                    return new Promise((success)=>{
                        success();
                    });
                }
            },
            //定位，如果是开发环境使用高德定位，生产使用微信环境
            location(){
                if(this.$sysinfo.develop){
                    return new Promise((success,error)=>{
                        this.map.location.getCurrentPosition((status,result)=>{
                            if(status == "complete"){
                                success(result.position);
                            }else{
                                error("定位失败");
                            }
                        });
                    });
                }else{
                    return new Promise((success,error)=>{
                        this.$wx.getLocation({
                            type: "gcj02",
                            success:(res)=>{
                                success([res.longitude,res.latitude]);
                            },
                            cancel:function(){
                                error("定位失败");
                            }
                        });
                    });
                }
            },
            //检测用户当前距离是否满足，分享奖励条件，对比用户位置到各个活动区域的中心位置距离，如果有一个距离小于生产奖励的距离则奖励有效，如果系统距离设置为0，则默认有效
            //param position 用户当前的定位
            testShareValid(position){
                if(this.share.take_m <= 0){
                    this.share.share_take = 1;
                    return;
                }else{
                    for(var i=0;i<this.activity_data.map_coords.length;i++){
                        var dis = this.$map.GeometryUtil.distance(position,this.activity_data.map_coords[i].center);
                        if(parseInt(this.take_m) >= parseInt(dis)){
                            this.share.share_take = 1;
                            return;
                        }
                    }
                }
            },
            //注册活动
            register(){
                this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                    pages:"activityA",
                    doing:"register",
                    uid:this.$sysinfo.uid,
                    activity_id:this.activity_id,
                    share_uid:this.share.share_uid,
                    share_take:this.share.share_take
                }))
                    .then((res)=>{
                        if(res.data.status == "success" && res.data.add_friend == 1){
                            this.$createToast({
                                type:"correct",
                                txt: "好友已添加"
                            }).show();
                        }
                    });
            },
            //获取用户未开宝箱和已开宝箱
            getUserOpenBzNumber(){
                return new Promise((success,error)=>{
                    this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                        pages:"activityA",
                        doing:"getUserOpenBzNumber",
                        init_bz_number:this.activity_data.init_bz_number,
                        activity_id:this.activity_id,
                        uid:this.$sysinfo.uid
                    }))
                        .then((res)=>{
                            if(res.data.status == "success"){
                                this.bz.already_open_number = res.data.data.already_open_number;
                                this.bz.can_open_number = res.data.data.can_open_number;
                                success();
                            }else{
                                error("获取用户可开宝箱和已开宝箱的数量");
                            }
                        })
                        .catch();
                });
            },
            //分享
            shareSetting(){
                this.getShareData()
                    .then((data)=>{
                        var shareData = {
                            title:data.name,
                            imgUrl:data.cover,
                            desc:data.brief,
                            link:data.share_url
                        };
                        this.$wx.onMenuShareAppMessage(shareData);
                        this.$wx.onMenuShareTimeline(shareData);
                    })
                    .catch();
            },
            //获取分享数据
            getShareData(){
                return new Promise((success)=>{
                    this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                        pages:"share",
                        doing:"share",
                        activity_id:this.activity_id,
                        uid:this.$sysinfo.uid
                    }))
                        .then((res)=>{
                            success(res.data.data);
                        })
                        .catch();
                });
            },
            //创建用户的mark
            createUserMark(position){
                this.map.user_mark = new this.$map.Marker({
                    map:this.map.map,
                    position:position,
                    angle:0,
                    zIndex:103,
                    anchor:"center",
                    offset:new this.$map.Pixel(0,0),
                    content:`<div id="user-mark">
                                <svg class="iconfont" aria-hidden="true">
                                    <use xlink:href="#icon-dingwei"></use>
                                </svg>
                              </div>`
                });
                //开启陀螺仪旋转
                var ua = navigator.userAgent.toLowerCase();
                if(/android/.test(ua)){
                    window.addEventListener("deviceorientation",(event)=>{
                        this.map.user_mark.setAngle(Math.round(360-event.alpha));
                    }, false);
                }else{
                    window.addEventListener("deviceorientation",(event)=>{
                        this.map.user_mark.setAngle(event.webkitCompassHeading);
                    }, false);
                }
            },
            //监听用户位置，实时改变定位小尾巴的位置
            listenUserLocation(){
                clearInterval(store.state.user_mark_timer);
                store.state.user_mark_timer = setInterval(()=>{
                    this.location()
                        .then((position)=>{
                            this.map.user_mark.setPosition(position);
                            if(this.bz.selected_bz){
                                this.bz.distance = this.distanceMath(position,this.bz.selected_bz.position);
                            }
                        })
                        .catch();
                },3000);
            },
            /**
             *设置宝藏的所有坐标，使用了html5缓存减少服务器和客户端压力
             */
             setBzLngLat(){
                var lnglat = this.$iSession.get("activity_"+this.activity_id+"_lnglat");
                if(!lnglat || this.activity_data.cache == 0){
                    lnglat = this.createBzLngLat();
                    this.$iSession.set("activity_"+this.activity_id+"_lnglat",lnglat);
                }
                this.bz.lnglat = lnglat;
            },
            /**
             * 创建生产宝箱经纬度
             * @param create_number
             * @returns {[]}
             */
            createBzLngLat(){
                var bz_array = [];
                var map_coords = this.activity_data.map_coords;
                for(let i=0;i<map_coords.length;i++){
                    var coords = map_coords[i].coords;
                    var southeast_lnglat = map_coords[i].bounds[0];  //区域的东北角坐标
                    var southwest_lnglat = map_coords[i].bounds[1];  //区域的西南角坐标
                    //计算区域的宝箱投放数量，如果后台没有设置投放数量，自动计算，如果设置了则使用设置好的数量
                    var put_number = 0;
                    if(this.activity_data.bz_number <= 0){
                        var area = map_coords[i].area / 1000000;
                        put_number = parseInt(area*700);
                        if(put_number > 500) put_number = 500;
                    }else{
                        put_number = this.activity_data.bz_number;
                    }
                    var temp_bz = [];
                    while (temp_bz.length < put_number){
                        var tempLngLat = this.randomLnglat(southeast_lnglat,southwest_lnglat);
                        if(this.$map.GeometryUtil.isPointInRing(tempLngLat,coords)){
                            temp_bz.push(tempLngLat);
                        }
                    }
                    bz_array.push({lnglat:temp_bz,number:put_number});
                }
                return bz_array;
            },
            //生成两个经纬度之间的随机经纬度
            randomLnglat(lnglat1,lnglat2){
                return [random.float(parseFloat(lnglat1[0]),parseFloat(lnglat2[0])),random.float(parseFloat(lnglat1[1]),parseFloat(lnglat2[1]))];
            },
            //往地图插入宝箱
            pushBz(){
                var markers = [];
                this.bz.lnglat.forEach((item,index)=>{
                    item.lnglat.forEach((item_a,index_a)=>{
                        var mark = new this.$map.Marker({
                            position:item_a,
                            offset:new this.$map.Pixel(0,0),
                            content:this.bz.default_style,
                        });
                        mark.position = item_a;
                        mark._index = [index,index_a];
                        mark.on("click",this.clickBz);
                        markers.push(mark);
                    });
                });
                this.map.map.add(markers);
            },
            //点击地图上的宝藏
            clickBz(event){
                if(this.bz.selected_bz){
                    this.bz.selected_bz.setContent(this.bz.default_style);
                }
                this.bz.selected_bz = event.target;
                this.bz.selected_bz.setContent(this.bz.selected_style);
                this.location()
                    .then((position)=>{
                        this.bz.distance = this.distanceMath(position,event.target.position);
                    })
                    .catch();
            },
            //两点距离计算
            distanceMath(p1,p2){
                return this.$map.GeometryUtil.distance(p1,p2);
            },
            //活动启动广告
            startAdver(){
                this.$http.post(this.$sysinfo.url,this.$qs.stringify({
                    pages:"adver",
                    doing:"frontFind",
                    activity_id:this.activity_id,
                    uid:this.$sysinfo.uid,
                }))
                    .then((res)=>{
                        if(res.data.status == "success"){
                            var data = res.data.data;
                            this.adver.show = true;
                            this.adver.src = data.src+"?time="+new Date().getTime();
                            this.adver.url = data.url;
                            clearInterval(store.state.start_adver_down_timer);
                            store.state.start_adver_down_timer = setInterval(()=>{
                                if(--this.adver.down <= 0){
                                    this.adver.show = false;
                                    clearInterval(store.state.start_adver_down_timer);
                                }
                            },1000);
                        }
                    })
                    .catch();
            },
        //E加载----------

        //S操作
            //点击活动定位按钮
            activityLocation(){
                this.activity_data.map_coords_index++;
                if(this.activity_data.map_coords_index > this.activity_data.map_coords.length-1){
                    this.activity_data.map_coords_index = 0;
                }
                this.map.map.setCenter(this.activity_data.map_coords[this.activity_data.map_coords_index].center);
            },
            //点击用户定位按钮
            userLocation(){
                this.location()
                    .then((position)=>{
                        this.map.map.setCenter(position);
                    })
                    .catch();
            },
            //显示好友列表
            showFriend(){
                this.friend_list.friend_transition = "friend-transition animated slideInRight faster";
                setTimeout(()=>{
                    this.friend_list.show = true;
                },100);
            },
            //关闭好友列表
            closeFriend(){
                this.friend_list.friend_transition = "friend-transition animated slideOutRight faster";
                setTimeout(()=>{
                    this.friend_list.show = false;
                },100);
            },
            //好友奖励领取成功
            friendAward(number){
                this.bz.can_open_number += number;
            },
            //点击启动广告
            clickAdver(){
                if(this.adver.url != ""){
                    window.location.href = this.adver.url;
                }
            },
        //E操作

        //S开宝箱---------
            //点击开宝箱按钮
            clickOpenBtn(){
                //1、检测是否可以开宝箱
                if(!this.openCheck()) return;
                //开宝箱
                this.open.step = 1;
                //开宝箱开启定时器
                setTimeout(()=>{
                    this.openBz()
                        .then((res_data)=>{
                            //开宝箱返回的数据
                            this.open.step = 2;
                            return this.disposeBzData(res_data);
                        })
                        .then((after)=>{
                            if(after){
                                //开宝箱成功后执行
                                // console.log(this.bz.selected_bz);
                                //1、新增宝箱开启数量
                                this.bz.already_open_number++;
                                //2、删除缓存中的宝箱经纬度
                                this.removeCacheLnglat();
                                //3、重新填充地图上的宝箱
                                this.fillBzLnglat();
                                //4、删除当前地图上的宝箱
                                this.map.map.remove(this.bz.selected_bz);
                                this.bz.selected_bz = null;
                            }
                        })
                        .catch();
                },2000);
            },
            //开宝箱前检测
            openCheck(){
                if(!this.bz.selected_bz){
                    this.$createToast({
                        time: 1000,
                        txt: "请选择一个宝箱",
                        type:"error",
                        mask:true
                    }).show();
                    return false;
                }
                if(this.activity_data.time_status != 2){
                    this.$createToast({
                        time: 1000,
                        txt: this.activity_data.time_status == 1 ? "活动未开始" : "活动已结束",
                        type:"error",
                        mask:true
                    }).show();
                    return false;
                }
                if((this.activity_data.open_distance > 0) && (this.bz.distance > this.activity_data.open_distance)){
                    this.$createToast({
                        time: 1000,
                        txt: "距离宝箱"+this.str_open_distance+"之内才可以打开",
                        type:"error",
                        mask:true
                    }).show();
                    return false;
                }
                if((this.activity_data.init_bz_number != 0) && (this.bz.already_open_number >= this.bz.can_open_number)){
                    this.$createToast({
                        time: 1000,
                        txt: "可开宝箱数量不足",
                        type:"error",
                        mask:true
                    }).show();
                    return false;
                }
                return true;
            },
            //服务器请求开宝箱
            openBz(){
                return new Promise((success)=>{
                    var requestData = {
                        pages:"openBz",
                        activity_id:this.activity_id,
                        uid:this.$sysinfo.uid,
                        bz_lng:this.bz.selected_bz.position[0],
                        bz_lat:this.bz.selected_bz.position[0],
                        timestamp:Date.now()
                    };
                    requestData.sign = this.getOpenBzMd5(requestData);
                    this.$http.post(this.$sysinfo.url,this.$qs.stringify(requestData))
                        .then((res)=>{
                            //this.open.step = 0;
                            success(res.data);
                        })
                        .catch();
                });
            },
            //开宝箱服务器请求所有参数字典序排序后返回MD5加密字符串
            getOpenBzMd5(data){
                var keys = Object.keys(data).sort();
                var key_str = "";
                for(var i=0;i<keys.length;i++){
                    key_str += data[keys[i]];
                }
                return Md5(key_str).toUpperCase();
            },
            //开宝箱后返回的数据处理
            disposeBzData(res_data){
                return new Promise((success)=>{
                    if(res_data.status == "success"){
                        var data = res_data.data;
                        if(data.type == 1 || data.type == 2){
                            this.open.bz = {
                                status:"success",
                                type:data.type,
                                name:data.name,
                                icon:data.icon
                            };
                        }else{
                            if(data.type == 3){
                                this.open.bz = {
                                    status:"success",
                                    type:data.type,
                                    name:data.name,  //卡券名字
                                    cover:data.cover,  //卡券封面
                                    store_name:data.store_name,   //所属门店名字
                                    store_logo:data.logo,  //所属门店logo
                                    coupon_type:data.coupon_type,   //卡券类型
                                    cost:data.cost,   //卡券面值
                                    cost_type:data.cost_type.substring(0,2),
                                    period:data.period  //卡券有效期
                                };
                            }else{
                                this.open.bz = {
                                    status:"success",
                                    type:data.type,
                                    name:data.name,  //卡券名字
                                    icon:data.icon,
                                    period:data.period  //卡券有效期
                                };
                            }
                        }
                        success(true);  //是否认定为宝箱开启成功
                    }else{
                        this.open.bz = {
                            status:"error",
                            err_msg:res_data.err_msg
                        };
                        if(res_data.err_status > 0){
                            success(true);  //是否认定为宝箱开启成功
                        }else{
                            success(false); //是否认定为宝箱开启成功
                        }
                    }
                });
            },
            //删除缓存中的宝箱经纬度
            removeCacheLnglat(){
                var cache_lnglat = this.$iSession.get("activity_"+this.activity_id+"_lnglat");
                cache_lnglat[this.bz.selected_bz._index[0]].lnglat.splice(this.bz.selected_bz._index[1],1);
                this.$iSession.set("activity_"+this.activity_id+"_lnglat",cache_lnglat);
            },
            //填充宝藏(宝藏经纬度)
            fillBzLnglat(){
                var cache_lnglat = this.$iSession.get("activity_"+this.activity_id+"_lnglat");
                var index_a = this.bz.selected_bz._index[0];
                var limit_number = parseInt(cache_lnglat[index_a].number * 0.8);
                if(cache_lnglat[index_a].lnglat.length <= limit_number){
                    var fill_lnglat = this.createFillBzLnglat(index_a,cache_lnglat[index_a].number - cache_lnglat[index_a].lnglat.length);
                    this.pushFillBz(index_a,fill_lnglat);
                    cache_lnglat[index_a].lnglat.push(...fill_lnglat);
                    this.$iSession.set("activity_"+this.activity_id+"_lnglat",cache_lnglat);
                }
            },
            /**
             *生成填充宝藏经纬度
             * @param index  填充区域的下标
             * @param number 填充数量
             * @return 返回数组
             */
            createFillBzLnglat(index,number){
                var lnglat = [];
                var coords = this.activity_data.map_coords[index].coords;
                var southeast_lnglat = this.activity_data.map_coords[index].bounds[0];
                var southwest_lnglat = this.activity_data.map_coords[index].bounds[1];
                while (lnglat.length < number){
                    var tempLngLat = this.randomLnglat(southeast_lnglat,southwest_lnglat);
                    if(this.$map.GeometryUtil.isPointInRing(tempLngLat,coords)){
                        lnglat.push(tempLngLat);
                    }
                }
                return lnglat;
            },
            /**
             *插入填充的宝藏
             * @oaram _index 填充区域的下标
             * @param lnglat
             */
            pushFillBz(_index,lnglat){
                var markers = [];
                lnglat.forEach((item,index)=>{
                    var mark = new this.$map.Marker({
                        position:item,
                        offset:new this.$map.Pixel(0,0),
                        content:this.bz.default_style,
                    });
                    mark.position = item;
                    mark._index = [_index,index];
                    mark.on("click",this.clickBz);
                    markers.push(mark);
                });
                this.map.map.add(markers);
            },
        //E开宝箱----------
    }
};
</script>

<style lang="less" scoped>
    #map{
        height:100%;
    }
    #open-btn{
        position:fixed;
        z-index:10;
        bottom:40px;
        left:112.5px;
        width:150px;
        border-radius: 50px;
        background: #FC9153 url('./images/open-bz.svg') 35px center no-repeat;
        text-indent: 40px;
        background-size:30px;
    }
    #can-open-number{
        position:fixed;
        z-index:10;
        bottom:95px;
        left:118px;
        width:140px;
        height:20px;
        line-height: 20px;
        border-radius: 20px;
        color:#fff;
        font-size:14px;
        text-align: center;
        background: rgba(252,145,83,1);
    }
    #header{
        position:fixed;
        z-index:10;
        top:10px;
        left:112.5px;
        width:150px;
    }
    #header .a{
        color:#fff;
    }
    #header .child{
        width:100%;
        height:25px;
        line-height: 25px;
        margin-bottom: 5px;
        background:rgba(252,145,83,.7);
        font-size:14px;
        text-align: center;
        border-radius: 12.5px;
        color:#fff;
    }
    #open-bz{
        position: fixed;
        z-index:20;
        top:0;
        left:0;
        bottom: 0;
        right: 0;
        background: rgba(0,0,0,.7);
    }
    #open-bz h3{
        margin-bottom: 20px;
    }
    #open-bz .close{
        color:#fff;
        font-size:40px;
    }
    #open-bz .open-bz{
        position: absolute;
        top:50%;
        transform: translateY(-50%);
        width: 100%;
        font-size:16px;
        text-align: center;
        color:#fff;
    }
    #open-bz .opening img.icon,#open-bz .opened img.icon{
        display: block;
        width:100px;
        margin:0 auto 10px auto;
    }
    #open-bz .opened img.icon{
        width: 200px;
    }
    #open-bz .error-iconfont{
        width:200px;
        margin-left: 30px;
    }
    #open-bz .open-bz .store{
        text-align: left;
        width:355px;
        height:50px;
        margin:0 auto 10px auto;
        background: red;
        box-sizing: border-box;
        padding:0 10px;
    }
    #open-bz .open-bz .store.dh{
        background: url("../images/dh-bg.png") no-repeat 0 -10px;
        background-size:cover;
    }
    #open-bz .open-bz .store.dj{
        background: url("../images/dj-bg.png") no-repeat 0 -10px;
        background-size:cover;
    }
    #open-bz .open-bz .store.mj{
        background: url("../images/mj-bg.png") no-repeat 0 -10px;
        background-size:cover;
    }
    #open-bz .open-bz .store.rc{
        background: url("../images/rc-bg.png") no-repeat 0 -10px;
        background-size:cover;
    }
    #open-bz .open-bz .store.zk{
        background: url("../images/zk-bg.png") no-repeat 0 -10px;
        background-size:cover;
    }
    #open-bz .open-bz .store .logo{
        float: left;
        width:40px;
        height:40px;
        border-radius: 20px;
        margin-top: 5px;
        border:2px solid #fff;
        box-sizing: border-box;
    }
    #open-bz .open-bz .store .name{
        float:left;
        width: 280px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        margin-left: 10px;
        line-height: 50px;
    }
    #open-bz .coupon{
        position: relative;
        width:355px;
        height:138px;
        margin: 0 auto 10px auto;
        padding:10px 10px 10px 15px;
        box-sizing: border-box;
        text-align: left;
        font-size:14px;
    }
    #open-bz .coupon.dh{
        background: url("../images/dh-bg.png") no-repeat center center;
        background-size:100% 100%;
    }
    #open-bz .coupon.mj{
        background: url("../images/mj-bg.png") no-repeat center center;
        background-size:100% 100%;
    }
    #open-bz .coupon.dj{
        background: url("../images/dj-bg.png") no-repeat center center;
        background-size:100% 100%;
    }
    #open-bz .coupon.zk{
        background: url("../images/zk-bg.png") no-repeat center center;
        background-size:100% 100%;
    }
    #open-bz .coupon.rc{
        background: url("../images/rc-bg.png") no-repeat center center;
        background-size:100% 100%;
    }
    #open-bz .coupon>.type{
        position: absolute;
        top:0;
        right:10px;
        height:30px;
        line-height: 30px;
        font-size:18px;
        color:#fff;
        text-shadow: 0 0 1px, 0 0 3px;
    }
    #open-bz .coupon img.cover{
        display: block;
        float:left;
        width:75px;
        height:75px;
        border:3px solid #fff;
        box-sizing: border-box;
        object-fit: cover;
        margin-right:10px;
    }
    #open-bz .coupon .cost{
        float: left;
        width:190px;
        font-size:18px;
        margin-bottom: 5px;
    }
    #open-bz .coupon .name{
        float: left;
        width:190px;
    }
    #open-bz .coupon .time{
        position: absolute;
        right:10px;
        bottom:10px;
    }
    #open-bz .sponsor-coupon{
        position: relative;
        width:355px;
        height:138px;
        margin: 0 auto 10px auto;
        background: url("../images/hd-bg.png") no-repeat center center;
        background-size:100% 100%;
        padding:10px 15px 0 15px;
        box-sizing: border-box;
    }
    #open-bz .sponsor-coupon img.icon{
        display: block;
        width:75px;
        height:75px;
        float:left;
        border:3px solid #fff;
        box-sizing: border-box;
        object-fit: cover;
    }
    #open-bz .sponsor-coupon .name{
        float:left;
        width: 210px;
        line-height: 110%;
        text-align: left;
        margin-left: 10px;
    }
    #open-bz .sponsor-coupon .time{
        position: absolute;
        bottom:10px;
        right:17px;
    }
    #adver{
        position:fixed;
        z-index:50;
        top:0;
        left:0;
        bottom:0;
        right: 0;
        background: rgba(0,0,0,.7);
    }
    #adver{
        width:375px;
        height:100%;
        background-size: 100% 100%;
        background-repeat: no-repeat;
    }
    #adver .down{
        position: absolute;
        right:10px;
        top:10px;
        width:100px;
        height:30px;
        line-height: 30px;
        text-align: center;
        border-radius: 15px;
        font-size:16px;
        background: rgba(0,0,0,.8);
        color:#fff;
    }
    .children{
        position: fixed;
        background: #fff;
        z-index:300;
        top:0;
        width: 375px;
    }
    .friend-transition{
        animation-duration: .5s;
        animation-delay: 0s;
    }
</style>

<style lang="stylus" rel="stylesheet/stylus">
    #main-scroll .cube-scroll-content,#main-scroll .cube-scroll-list-wrapper
        height:100%;
    #user-mark
        width:30px;
        height:30px;
        text-align:center;
        font-size:30px;
        z-index:10000;
        transform:rotate(180deg);
    /*地图上宝箱的默认样式*/
    .default_bz_style
        position:relative;
        width:30px;
        height: 30px;
        border-radius 15px;
        border:3px solid #fff;
        box-sizing:border-box;
        background: #FC9153;
        text-align:cetner;
    .selected_bz_style
        background:red !important;
    .default_bz_style .self-iconfont
        position:absolute;
        width:20px;
        height:20px;
        top:50%;
        left:2px;
        transform:translateY(-50%);
    .cube-toast-tip
        max-width:300px !important;
</style>
